
const Util = require('Util');
const Level = require('Level');
const RoadBlockFactory = require('RoadBlockFactory');


const LvNumMap = {
    1: 2,
    2: 5,
    3: 4,
    4: 3,
    5: 4,
    6: 7
};


let LevelFactory = function () {
    this.lastLevelId = Object.keys(LvNumMap).pop();

    this.lvMap = {};

    for (let i = 0, keys = Object.keys(LvNumMap), key; key = keys[i++];) {
        this.lvMap[key] = {};
    }

    this.isInited = false;
};

LevelFactory.prototype = {
    constructor: LevelFactory,

    init(callback) {
        let tasks = [];

        let initLvId = 1;
        for (let lvIdx = 1; lvIdx <= LvNumMap[initLvId]; lvIdx++) {
            tasks.push((done) => {
                this.loadFile('lv-' + initLvId + '-' + lvIdx, done);
            });
        }

        Util.series(tasks, () => {
            RoadBlockFactory.init(() => {
                this.isInited = true;

                callback();
            });
        });
    },

    loadFile(name, callback) {
        let [prefix, lvId, lvIdx] = name.split('-');

        cc.loader.loadRes('level/'+ name, (err, jsonAsset) => {
            if (err) {
                cc.error(`Load level json error: ${err}`);
                return;
            }

            let lvStr = jsonAsset.json.data;

            this.lvMap[lvId][lvIdx] = lvStr;

            callback(lvStr);
        });
    },

    createLevel(lvId, lvIdx, callback) {
        let name = `lv-${lvId}-${lvIdx}`;

        let lvStr = this.lvMap[lvId][lvIdx];
        if (!lvStr) {
            this.loadFile(name, (lvStr) => {
                let levelNode = Level.createNodeWithString(lvStr);
                levelNode.name = name;
                callback( levelNode.getComponent('Level') );
            });
            return;
        }

        let levelNode = Level.createNodeWithString(lvStr);
        levelNode.name = name;
        callback( levelNode.getComponent('Level') );
    },

    generateLevel(lvId, callback) {
        return this.createLevel(lvId, Util.randomInt(1, LvNumMap[lvId]), callback);
    }
};

module.exports = new LevelFactory();